package net.uman.framework.jms;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Destination;

import net.uman.entity.IdEntity;
import net.uman.framework.modules.search.FieldDesc;

import org.springframework.jms.core.JmsTemplate;

/**
 * JMS消息生产者.
 * 
 * 使用jmsTemplate将String消息分别发送到queue与topic.
 * 
 * @author Bob Chen
 */
public class SearchSaveMessageProducer {

	private JmsTemplate jmsTemplate;
	private Destination notifyQueue;

	public void deleteDocument(IdEntity entity) {
		String name = entity.getClass().getSimpleName();
		
		Map<String, Object> msg = new HashMap<String, Object>();
		msg.put("^action^", "delete");
		msg.put("^name^", name);
		msg.put("^id^", entity.getId());
		sendMessage(msg, notifyQueue);		
	}
	
	public void saveDocument(IdEntity entity, String[] fields) {
		String name = entity.getClass().getSimpleName();
		Long id = entity.getId();
		
		int i = 0;
		FieldDesc[] flds = new FieldDesc[fields.length];
		for (String f : fields) {
			FieldDesc fd = new FieldDesc();
			fd.setName(f);
			fd.setSearchable(true);
			Object value = getValue(entity, f);
			fd.setValue(value == null ? null : value.toString());
			
			flds[i++] = fd;
		}
		
		saveDocument(name, id, flds);
	}
	
	private Object getValue(IdEntity entity, String fld) {
		fld = fld.substring(0, 1).toUpperCase() + fld.substring(1); 
		try {
			Method m = entity.getClass().getMethod("get"+fld, new Class[0]);
			Object value = m.invoke(entity, new Object[0]);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void saveDocument(String name, Long id, FieldDesc[] flds) {
		Map<String, Object> msg = new HashMap<String, Object>();
		msg.put("^action^", "save");
		msg.put("^name^", name);
		msg.put("^id^", id);
		for (FieldDesc fld : flds) {
			String s = (fld.isSearchable() ? "1" : "0")+"|"+fld.getValue();
			msg.put(fld.getName(), s);
		}
		sendMessage(msg, notifyQueue);
	}

	private void sendMessage(final Map msg, Destination destination) {
		try{
			jmsTemplate.convertAndSend(destination, msg);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public void setNotifyQueue(Destination notifyQueue) {
		this.notifyQueue = notifyQueue;
	}
}
